package com.atguigu.srb.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.TransTypeEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.TransFlowMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.BO.TransFlowBO;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.util.LendNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author ZLHao
 * @since 2021-07-12
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private  UserInfoMapper userInfoMapper;

    @Autowired
    private TransFlowService transFlowService;



    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {

        // 这里就是为了拿到bindcode
        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();
        //判断账户绑定状态
        Assert.notEmpty(bindCode, ResponseEnum.USER_NO_BIND_ERROR);


        // 开始组织post 表单的内容
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("chargeAmt", chargeAmt); // 充值金额
        paramMap.put("feeAmt", new BigDecimal("0")); // 充值不收取费用
        paramMap.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);//检查常量是否正确
        paramMap.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        String formStr = FormHelper.buildForm(HfbConst.RECHARGE_URL, paramMap);
        return formStr;
    }

    @Override
    public String notify(Map<String, Object> paramMap) {


        String agentBillNo = (String)paramMap.get("agentBillNo"); //商户充值订单号
        //  先判断接口的幂等性，看是否重复调用
        boolean saveTransFlow = transFlowService.isSaveTransFlow(agentBillNo);

        if (saveTransFlow){
            log.info("幂等性返回");
            return "success";
        }




        log.info("充值成功：" + JSONObject.toJSONString(paramMap));

        String bindCode = (String)paramMap.get("bindCode"); //充值人绑定协议号
        String chargeAmt = (String)paramMap.get("chargeAmt"); //充值金额

        //优化， 本地修改完成充值金额；
        baseMapper.updateAccount(bindCode, new BigDecimal(chargeAmt), new BigDecimal(0));

        //增加交易流水


        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,  // 充值订单号
                bindCode,    //  code
                new BigDecimal(chargeAmt), // 充值金额
                TransTypeEnum.RECHARGE,
                "充值");

        transFlowService.saveTransFlow(transFlowBO);



        // 测试幂等性  当没有先判断数据库是否存在重复的充值号时，此时fhb会不断调用5次，本地数据就会相应的增加5次充值金额；
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return "success";
    }

    @Override
    public BigDecimal getAccount(Long userId) {

        QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);

        UserAccount userAccount = baseMapper.selectOne(queryWrapper);
        BigDecimal amount = userAccount.getAmount();
        return amount;
    }
}
